/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    vector<int> postorderTraversal(TreeNode *root)
    {
        if (root == nullptr)
        {
            return {};
        }
        vector<int> result;
        stack<TreeNode *> s;
        unordered_set<TreeNode *> visited;
        visited.insert(root);
        s.push(root);
        while (!s.empty())
        {
            TreeNode *cur = s.top();

            if (cur->right != nullptr && !visited.count(cur->right))
            {
                s.push(cur->right);
                visited.insert(cur->right);
            }
            if (cur->left != nullptr && !visited.count(cur->left))
            {
                s.push(cur->left);
                visited.insert(cur->left);
            }
            if (s.top() == cur)
            {
                result.push_back(cur->val);
                s.pop();
            }
        }
        return result;
    }
};